

package com.maoshi.shop.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.bean.enums.OfflineHandleEventType;
import com.maoshi.shop.bean.enums.ProdType;
import com.maoshi.shop.bean.event.ProdChangeStatusEvent;
import com.maoshi.shop.bean.model.OfflineHandleEvent;
import com.maoshi.shop.bean.model.Product;
import com.maoshi.shop.bean.model.Sku;
import com.maoshi.shop.bean.param.OfflineHandleEventAuditParam;
import com.maoshi.shop.bean.param.ProductParam;
import com.maoshi.shop.bean.param.ProductScoreParam;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.security.platform.util.SecurityUtils;
import com.maoshi.shop.service.BasketService;
import com.maoshi.shop.service.OfflineHandleEventService;
import com.maoshi.shop.service.ProductService;
import com.maoshi.shop.service.SkuService;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;


/**
 * 商品列表、商品发布controller
 *
 * @author lgh
 */
@Controller
@RequestMapping("/prod/prod")
@AllArgsConstructor
public class ProductController {

    private final ProductService productService;
    private final SkuService skuService;
    private final BasketService basketService;
    private final ApplicationContext applicationContext;
    private final OfflineHandleEventService offlineHandleEventService;


    /**
     * 分页获取商品信息
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('prod:prod:page')")
    public ResponseEntity<IPage<Product>> page(ProductParam product, PageParam<Product> page) {
       /* IPage<Product> products = productService.page(page,
                new LambdaQueryWrapper<Product>()
                        .like(StrUtil.isNotBlank(product.getProdName()), Product::getProdName, product.getProdName())
                        .eq(product.getStatus() != null, Product::getStatus, product.getStatus())
                        .orderByDesc(Product::getPutawayTime)
                        .ne(Product::getStatus,-1));*/
       //TODO gai eq(Product::getProdType,ProdType.PROD_TYPE_NORMAL)
        IPage<Product> products = productService.getPageAngShopName(page,product);
        return ResponseEntity.ok(products);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:info')")
    public ResponseEntity<Product> info(@PathVariable("prodId") Long prodId) {
        Product prod = productService.getProductByProdId(prodId);
        List<Sku> skuList = skuService.listByProdId(prodId);
        prod.setSkuList(skuList);
        return ResponseEntity.ok(prod);
    }

    /**
     * 平台删除商品
     */
    @DeleteMapping("/{prodId}")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ResponseEntity<Void> delete(@PathVariable("prodId") Long prodId) {
        Product dbProduct = productService.getProductByProdId(prodId);
        List<Sku> dbSkus = skuService.listByProdId(dbProduct.getProdId());
        // 删除商品
        productService.removeProductByProdId(prodId);

        for (Sku sku : dbSkus) {
            skuService.removeSkuCacheBySkuId(sku.getSkuId(), sku.getProdId());
        }

        List<String> userIds = basketService.listUserIdByProdId(prodId);

        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }

        return ResponseEntity.ok().build();
    }

    /**
     * 下线活动
     */
    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('prod:prod:update')")
    public ResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Product dbProduct = productService.getProductByProdId(offlineHandleEvent.getHandleId());
        if (dbProduct == null) {
            throw new MaoshiShopBindException("未找到刚商品的信息");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        productService.offline(offlineHandleEvent.getHandleId(), offlineHandleEvent.getOfflineReason(), sysUserId);

        // 商品状态改变时的发送事件，让活动下线
        applicationContext.publishEvent(new ProdChangeStatusEvent(dbProduct, dbProduct.getStatus()));
        List<String> userIds = basketService.listUserIdByProdId(dbProduct.getProdId());
        for (String userId : userIds) {
            basketService.removeShopCartItemsCacheByUserId(userId);
        }
        // 移除缓存
        productService.removeProductCacheByProdId(dbProduct.getProdId());
        return ResponseEntity.ok().build();
    }

    /**
     * 通过prodId获取最新下线商品的事件
     */
    @GetMapping("/getOfflineHandleEventByProdId/{prodId}")
    public ResponseEntity<OfflineHandleEvent> getOfflineHandleEventByProdId(@PathVariable Long prodId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.PROD.getValue(), prodId);
        return ResponseEntity.ok(offlineHandleEvent);
    }

    /**
     * 审核商品
     */
    @PostMapping("/prodAudit")
    public ResponseEntity<Void> prodAudit(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long userId = SecurityUtils.getSysUser().getUserId();
        productService.prodAudit(offlineHandleEventAuditParam, userId);

        // 移除缓存
        productService.removeProductCacheByProdId(offlineHandleEventAuditParam.getHandleId());
        return ResponseEntity.ok().build();
    }

}
